package com.qhgrain.app.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.paas.base.modules.utils.lang.StringUtil;
import com.qhgrain.app.constant.UrlEnum;
import com.qhgrain.app.util.ConfigUtil;
import com.qhgrain.app.vo.PermissionInfo;
import com.qhgrain.gway.util.HttpUtil;
@Service
public class PermissionService {

	private static Logger LOG = LoggerFactory.getLogger(PermissionService.class);
	
	private final static String BASE_URL = ConfigUtil
			.getProperties(UrlEnum.MENU_ROLE_PERMISSION)+"/permission";
	
	
	public JSONArray queryByMenuIds(List<String> menuIds) throws Exception{
		String ids = StringUtils.join(menuIds,",");
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("menuIds", ids);
		String vo = HttpUtil.postFormParams(BASE_URL,"/query/bymenus", map);
		JSONObject voJson = JSONObject.parseObject(vo);
		if("1".equals(voJson.getString("state"))){
			return voJson.getJSONArray("data");
		}else{
			LOG.error("根据menuIds从api获取数据失败...");
			throw new RuntimeException("根据menuIds从api获取数据失败!");
		}
	}
	
	public List<PermissionInfo> queryByUserApp(String userId,String appId,String permissionType)throws Exception{
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("userId", userId.trim());
		map.put("appId", appId.trim());
		if(StringUtil.isNotBlank(permissionType)){
			map.put("permissionType", permissionType);
		}
		String vo = HttpUtil.post(BASE_URL+"/queryByUserApp", map);
		JSONObject voJson = JSONObject.parseObject(vo);
		if("1".equals(voJson.getString("state"))){
			return JSONArray.parseArray(voJson.getString("data"), PermissionInfo.class);
		}else{
			LOG.error("根据用户-应用的权限，api失败...map="+map+"...vo="+vo);
			throw new RuntimeException("根据用户-应用的权限，api失败...map="+map+"...vo="+vo);
		}
	}
	
	public List<PermissionInfo> queryByRoleApp(String roleId,String appId,String permissionType)throws Exception{
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("roleId", roleId.trim());
		map.put("appId", appId.trim());
		if(StringUtil.isNotBlank(permissionType)){
			map.put("permissionType", permissionType);
		}
		String vo = HttpUtil.post(BASE_URL+"/queryByRoleApp", map);
		JSONObject voJson = JSONObject.parseObject(vo);
		if("1".equals(voJson.getString("state"))){
			return JSONArray.parseArray(voJson.getString("data"), PermissionInfo.class);
		}else{
			LOG.error("根据角色-应用的权限，api失败...map="+map+"...vo="+vo);
			throw new RuntimeException("根据角色-应用的权限，api失败...map="+map+"...vo="+vo);
		}
	}
}
